package com.cloudlinkscm.loms.services.base.notify.scheduler;

import com.cloudlinkscm.loms.services.base.notify.constant.SendStatusEnum;
import com.cloudlinkscm.loms.services.base.notify.domain.email.EmailMessageManager;
import com.cloudlinkscm.loms.services.base.notify.dto.SendResultDto;
import com.cloudlinkscm.loms.services.base.notify.model.entity.EmailMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : tac
 * @date : 2017/6/21
 */


@Component
public class NotificationJob {
    public static final int NUM_OF_PER_SEND = 100;
    private static boolean SENDING_EMAIL = false;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final Object SENDING_EMAIL_LOCK = new Object();

    @Autowired
    private EmailMessageManager emailMessageManager;

    @Scheduled(cron = "*/10 * *  * * *")
    public void doEmailNotify(){
        boolean flag = false;
        synchronized (SENDING_EMAIL_LOCK){
            if(!SENDING_EMAIL){
                flag = true;
                SENDING_EMAIL = true;
            }
        }

        if(flag){
            logger.info("job running: send email");
            List<EmailMessage> messages = emailMessageManager.listMessage4Send(NUM_OF_PER_SEND).getList();

            while (messages.size() > 0){
                //todo:: 这里应该通过多线程去发送，以提高效率
                for (EmailMessage message : messages){
                    sendEmail(message);
                }
                messages = emailMessageManager.listMessage4Send(NUM_OF_PER_SEND).getList();
            }

            logger.info("job finished: send email");
            SENDING_EMAIL = false;
        }
    }

    private void sendEmail(EmailMessage message) {
        SendResultDto result = emailMessageManager.send(message);
        if (result.getState().equals(SendStatusEnum.SENT.val)) {
            emailMessageManager.setStatus(message.getId(), SendStatusEnum.SENT);
        }else{
            emailMessageManager.setStatus(message.getId(), SendStatusEnum.FAILURE);
            emailMessageManager.plusOneResendNum(message.getId());
        }
    }
}
